﻿using System;
using System.Data;
using System.Web.Script.Services;
using System.Web.Services;
using Webapp;
using EnumKeys;
using System.Web;
namespace xundh.API.CRM
{
    /// <summary>
    ///CRM_Customers 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.lansezhongjie.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]

    public class CRM_Buyers : BaseService
    {
        [WebMethod(EnableSession = true)]
        public ServiceStateKeys Add(int CustomerId, decimal WantUnitPriceBegin, decimal WantUnitPriceEnd, decimal WantTotalPriceBegin, decimal WantTotalPriceEnd,
            string WantDecoration, string CustomerName, int ViewLevel, string Tel, string Mem,
            int State, string WantRegionArea, decimal WantHouseAreaBegin, decimal WantHouseAreaEnd, string WantFloor, int Sex,
            string WantBuildingIds_Names, string WantBuildingIds, string Residence, string CRMType, int InformationComeFrom, int WantShi, int WantTing
            )
        {
            ///Session
            if (U == null) return ServiceStateKeys.TimeOut;
            ///参数处理
            WantDecoration = StringUtil.CutBadSqlInfo(WantDecoration);
            CustomerName = StringUtil.CutBadSqlInfo(CustomerName);
            Tel = StringUtil.CutBadSqlInfo(Tel);
            Mem = StringUtil.CutBadSqlInfo(Mem);
            WantRegionArea = StringUtil.CutBadSqlInfo(WantRegionArea);
            WantFloor = StringUtil.CutBadSqlInfo(WantFloor);
            Residence = StringUtil.CutBadSqlInfo(Residence);

            xundh.BLL.CRM_Buyers bll = new xundh.BLL.CRM_Buyers();
            xundh.Model.CRM_Buyers m;
            if (CustomerId > 0)
            {
                m = bll.GetModel(CustomerId);
                //权限
                if (m.AddUserId != U.UserId && m.ManageUserId != U.UserId)
                {
                    return ServiceStateKeys.NoPermiss;
                }
            }
            else
            {
                m = new xundh.Model.CRM_Buyers();
                m.AddTime = NOW;
                m.AddIp = IP;
                m.AddDepartId = U.DepartId;
                m.AddUserId = U.UserId;
                m.AddUser = U.UserName;
                m.ManageDepartId = U.DepartId;
                m.ManageUser = U.UserName;
                m.ManageUserId = U.UserId;
            }
            m.InformationComeFrom = InformationComeFrom;
            m.CRMType = CRMType;
            m.CustomerName = CustomerName;
            m.WantUnitPriceBegin = WantUnitPriceBegin;
            m.WantUnitPriceEnd = WantUnitPriceEnd;
            m.WantTotalPriceBegin = WantTotalPriceBegin;
            m.WantTotalPriceEnd = WantTotalPriceEnd;
            m.WantDecoration = WantDecoration;
            m.ViewLevel = ViewLevel;
            m.Sex = Sex;
            m.Tel = Tel;
            m.Mem = Mem;
            m.State = State;
            m.WantRegionArea = WantRegionArea;
            m.WantHouseAreaBegin = WantHouseAreaBegin;
            m.WantHouseAreaEnd = WantHouseAreaEnd;
            m.WantFloor = WantFloor;
            m.LastTime = NOW;
            m.LastIp = IP;
            m.LastDepartId = U.DepartId;
            m.LastUserId = U.UserId;
            m.LastUser = U.UserName;
            m.WantBuildingIds = WantBuildingIds;
            m.WantBuildings = WantBuildingIds_Names;
            m.Residence = Residence;
            m.WantShi = WantShi;
            m.WantTing = WantTing;
            if (CustomerId > 0)
                bll.Update(m);
            else
                bll.Add(m);
            return ServiceStateKeys.Success;
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public JsonTable GetLists(int page, int rows)
        {
            if (U == null) return null;
            xundh.BLL.BasePager bll = new BLL.BasePager();
            //权限
            //角色权限
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            if (!serviceOperation.CheckResouceOperationLimit(U.UserId, "客源管理", "查")) return null;
            int txtDeparts = StringUtil.GetIntValue(REQUEST["txtDeparts"]);
            string txtUserName = StringUtil.GetNullToString(REQUEST["UserId"]);
            string CustomerName = StringUtil.TBCode(StringUtil.GetNullToString(REQUEST["CustomerName"]));
            string txtAddTime = StringUtil.GetNullToString(REQUEST["AddTime"]);
            string txtMobile = StringUtil.GetNullToString(REQUEST["txtMobile"]).Trim();

            string where = " 1=1 ";

            if (txtDeparts > 1)
            {
                where += " AND AddDepartId=" + txtDeparts;
            }
            if (StringUtil.IsInt(txtUserName))
                where += " AND AddUserId=" + txtUserName;
            else if (txtUserName != "")
                where += " AND AddUser='" + txtUserName + "'";
            if (CustomerName != "")
                where += " AND CustomerName LIKE '%" + CustomerName + "%'";
            if (txtAddTime != "")
            {
                if (txtAddTime.IndexOf(',') > -1)
                {
                    string[] txtAddTimes = txtAddTime.Split(',');
                    if (StringUtil.isDate(txtAddTimes[0]) && StringUtil.isDate(txtAddTimes[1]))
                    {
                        where += " AND AddTime Between '" + txtAddTimes[0] + "' AND '" + txtAddTimes[1] + "'";
                    }
                }
                else
                {
                    where += " AND AddTime >='" + txtAddTime + "'";
                }
            }
            if (txtMobile != "")
                where += " AND Tel LIKE '%" + txtMobile + "%'";
            ///可见性权限 
            if (serviceOperation.CheckResouceOperationLimit(U.UserId, "客源管理", "查所有"))
            {

            }
            else if (serviceOperation.CheckResouceOperationLimit(U.UserId, "客源管理", "查部门"))
            {
                where += " AND (";
                where += " (AddUserId=" + U.UserId + " OR ManageUserId=" + U.UserId + ")";
                where += " OR ( AddDepartId=" + U.DepartId + ") OR (ManageDepartId=" + U.DepartId + ")";
                where += " OR ( ViewLevel=" + (int)HouseViewLevel.All + ")";
                where += " ) ";
            }
            else
            {
                where += " AND (";
                where += " (AddUserId=" + U.UserId + " OR ManageUserId=" + U.UserId + ")";
                where += " OR ( ViewLevel=" + (int)HouseViewLevel.Depart + " AND (AddDepartId=" + U.DepartId + " OR ManageDepartId=" + U.DepartId + "))";
                where += " OR ( ViewLevel=" + (int)HouseViewLevel.All + ")";
                where += " ) ";
            }
            string table = "CRM_Buyers";
            where += " AND State=0";
            JqGridHandler datagrid = new JqGridHandler(where);
            int recordcount = bll.GetAllCount(datagrid.StrWhere, table);

            string cols = "CustomerId,InformationComeFrom,CRMType,IsFirstBuy,WantRegionArea,WantHouseAreaBegin,WantHouseAreaEnd,WantHuxing,WantFloor,WantUnitPriceBegin,WantTotalPriceBegin,WantUnitPriceEnd,WantShi,WantTing,WantTotalPriceEnd,CustomerName,WantDecoration,WantBuildingIds,WantBuildings,AddTime,AddIp,AddDepartId,AddUserId,AddUser,LastTime,LastIp,ViewLevel,LastDepartId,LastUserId,LastUser,Sex,Tel,Mem,State,Residence,InformationSource,ManageUser";
            datagrid.init(datagrid.StrWhere, page, recordcount, rows, "", "");
            if (datagrid.Order == "") datagrid.Order = "CustomerId DESC";

            using (DataSet ds = bll.GetPager(datagrid.Pagesize, datagrid.P, datagrid.StrWhere, datagrid.Order, table, cols))
            {
                return new JsonTable(ds.Tables[0], recordcount, datagrid.P, datagrid.Recordcount);
            }
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public xundh.Model.CRM_Buyers Query(int id)
        {
            if (U == null) return null;
            xundh.BLL.CRM_Buyers bll = new xundh.BLL.CRM_Buyers();
            xundh.Model.CRM_Buyers m = bll.GetModel(id);
            RBAC.RBAC_Users serviceOperation = new RBAC.RBAC_Users();
            //权限
            bool hasLimit = false;
            if (m.AddUserId == U.UserId || m.ManageUserId == U.UserId)
            {
                hasLimit = true;
            }
            else if (serviceOperation.CheckResouceOperationLimit(U.UserId, "客源管理", "查所有"))
            {
                hasLimit = true;
            }
            else if (serviceOperation.CheckResouceOperationLimit(U.UserId, "客源管理", "查部门"))
            {
                if (m.AddDepartId == U.DepartId || m.ManageDepartId == U.DepartId) hasLimit = true;
            }
            else
            {
                //没有设定权限的，根据客户自身权限
                if (m.ViewLevel == (int)HouseViewLevel.Depart)
                {
                    if (m.AddDepartId == U.DepartId || m.ManageDepartId == U.DepartId) hasLimit = true;
                }
                else if (m.ViewLevel == (int)HouseViewLevel.All)
                {
                    hasLimit = true;
                }
            }
            if (!hasLimit) return null;
            return m;
        }

        [WebMethod(EnableSession = true)]
        public ServiceStateKeys UpdateState(int id, int State)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            //权限 只能修改自己的
            xundh.BLL.CRM_Buyers bll = new xundh.BLL.CRM_Buyers();
            xundh.Model.CRM_Buyers m = bll.GetModel(id);
            if (m == null) return ServiceStateKeys.NotExists;
            if (m.AddUserId != U.UserId || m.ManageUserId != U.UserId)
                return ServiceStateKeys.NoPermiss;
            m.State = State;
            m.LastDepartId = U.DepartId;
            m.LastIp = IP;
            m.LastTime = NOW;
            m.LastUser = U.UserName;
            m.LastUserId = U.UserId;
            bll.Update(m);
            return ServiceStateKeys.Success;
        }
        [WebMethod(EnableSession = true, Description = "重新分配")]
        [ScriptMethod(UseHttpGet = true)]
        public ServiceStateKeys Distribute(int id, int ManageUserId)
        {
            if (U == null) return ServiceStateKeys.TimeOut;

            xundh.BLL.CRM_Buyers bll = new xundh.BLL.CRM_Buyers();
            xundh.Model.CRM_Buyers m = bll.GetModel(id);
            if (m == null) return ServiceStateKeys.NotExists;
            //权限 修改自己的,或者有修改权限的
            RBAC.RBAC_Users serviceRBACUsers = new RBAC.RBAC_Users();

            if (m.AddUserId != U.UserId && m.ManageUserId != U.UserId)
            {
                if (serviceRBACUsers.CheckResouceOperationLimit(U.UserId, "客源管理", "改"))
                {

                }
                else
                {
                    return ServiceStateKeys.NoPermiss;
                }
            }
            else
            {

            }
            m.ManageUserId = ManageUserId;
            xundh.Model.RBAC_Users mManage = serviceRBACUsers.Query(ManageUserId);
            if (mManage == null) return ServiceStateKeys.NotExists;
            m.ManageUser = mManage.UserName;
            m.ManageDepartId = mManage.DepartId;
            m.LastDepartId = U.DepartId;
            m.LastIp = IP;
            m.LastTime = NOW;
            m.LastUser = U.UserName;
            m.LastUserId = U.UserId;
            m.DistributeDepartId = U.DepartId;
            m.DistributeTime = NOW;
            m.DistributeUser = U.UserName;
            m.DistributeUserId = U.UserId;
            bll.Update(m);
            return ServiceStateKeys.Success;
        }
    }
}

public enum CustomerSex { Female, Male, Unknown }
public enum CustomerState { Normal, Stop, Delete }
public enum CustomerViewLevel { Self, Depart, All }
public enum CRMType { Buy, Rent, Anjie, Diya }
public enum CustomerInformationComeFrom
{
    Network, ComeStore, DM, Frend, OldCustomer, Other
}